package com.xls.future.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.Intents;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xls.future.FutureApp;
import com.xls.future.R;
import com.xls.future.adapter.StaggeredAdapter;
import com.xls.future.entity.GroupData;
import com.xls.future.entity.Photo;
import com.xls.future.model.TopState;
import com.xls.future.presenter.HomePresenter;
import com.xls.future.presenter.HomePresenterImpl;
import com.xls.future.utils.GlideImageLoader;
import com.xls.future.utils.LogUtil;
import com.xls.future.utils.MyAnimatorListener;
import com.xls.future.utils.ScreenUtil;
import com.xls.future.utils.SpaceItemDecoration;
import com.xls.future.view.HomeView;
import com.xls.future.widget.StaggerRecyclerView;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;

import static com.google.zxing.integration.android.IntentIntegrator.REQUEST_CODE;

/**
 * Created by Administrator on 2017/8/22.
 */

public class HomeFragment extends BaseFragment implements HomeView, StaggerRecyclerView.OnLoadMoreListener {

    private final static String TAG = "HomeFragment";
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    Unbinder unbinder;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rvListView)
    StaggerRecyclerView rvListView;
    @BindView(R.id.btn_center)
    Button btnCenter;
    @BindView(R.id.cl_container)
    ConstraintLayout clContainer;

    private boolean isCollapsed = false;
    private TopState topState;
    private String curName = null;
    private List<String> bannerUrls;
    private HomePresenter mHomePresenter;
    private StaggeredAdapter mAdapter;

    private List<Button> buttons;
    private int detalDistance = 0;

    private TopButtonListener topButtonListener;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d("xls","HomeFragment onAttach");
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHomePresenter = new HomePresenterImpl(getContext(), this);
        mAdapter = new StaggeredAdapter(getActivity());
        Log.d("xls","HomeFragment onCreate");
        buttons = new ArrayList<>();
        topButtonListener = new TopButtonListener();
        topState = TopState.IDLE;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d("xls","HomeFragment onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("xls","HomeFragment onResume");
        if(isFirstVisible){
            LogUtil.d("xiong","HomeFragment 第一次可见");

        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("xls","HomeFragment onCreateView");
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        initViews();
        mHomePresenter.loadPicsForBanner();
        mHomePresenter.loadPicsForStaggerList(null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("xls","HomeFragment onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("xls","HomeFragment onDetach");
    }

    private void initViews() {
        if (getActivity() instanceof AppCompatActivity) {
            ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        }
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    //展开
                    setToolbarAlpha(0);
                    isCollapsed = false;
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    //收缩
                    setToolbarAlpha(255);
                    isCollapsed = true;
                } else {
                    int alpha = 255 * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange();
                    setToolbarAlpha(alpha);
                    isCollapsed = false;
                }
            }
        });

        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        banner.setBannerAnimation(getRandomPageTransformer());
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String url = bannerUrls.get(position);
                LogUtil.d(TAG, "OnBannerClick：" + position+" | "+url);
            }
        });

        final StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        sglm.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        rvListView.setLayoutManager(sglm);
        rvListView.setHasFixedSize(true);
        rvListView.addItemDecoration(new SpaceItemDecoration(2, ScreenUtil.dip2Px(4, getContext())));
        rvListView.setAdapter(mAdapter);
        rvListView.setOnLoadMoreListener(this);


    }

    private void initTopButtons(){
        List<GroupData> groupDatas = FutureApp.getInst().getGroups();
        LogUtil.d(TAG,"groupDatas size  ="+(groupDatas==null?null:groupDatas.size()));
        if(groupDatas==null || groupDatas.size()==0){
            return;
        }
        List<GroupData> tempList = new ArrayList<>();
        //随机变化规则
        if(groupDatas.size()>5){
            Collections.shuffle(groupDatas);
            tempList.addAll(groupDatas.subList(0,5));
        }else{
            tempList.addAll(groupDatas);
        }
        for(Button button:buttons){
            clContainer.removeView(button);
        }
        buttons.clear();

        for(GroupData groupData:tempList){
            buttons.add(createTopButton(clContainer,groupData.getName()));
        }


        detalDistance = (ScreenUtil.getScreenWidth(getContext())-ivScan.getWidth())/(buttons.size()+1);
        LogUtil.d(TAG,"buttons size ="+buttons.size()+" | detalDistance = "+detalDistance);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.d("xls","HomeFragment onHiddenChanged : "+hidden);
        if (hidden) {
            //隐藏
            isFirstVisible = false;
        } else {
            //显示
            LogUtil.d("xiong","HomeFragment 显示");
        }
    }

    @Override
    public void onLoadMore() {
        Log.d("home", "onLoadMore");
        mHomePresenter.loadPicsMore(curName,mAdapter.getItemCount());
    }

    @Override
    public void bindDataToBanner(List<Photo> photos) {
        if (bannerUrls == null) {
            bannerUrls = new ArrayList<>();
        } else {
            bannerUrls.clear();
        }

        for (Photo photo : photos) {
            bannerUrls.add(photo.getImgUrl());
        }
        banner.setImages(bannerUrls);
        banner.start();
    }

    @Override
    public void bindDataToStaggered(List<Photo> photos, boolean isLoadMore) {
        if (isLoadMore) {
            //加载更多
            mAdapter.addData(photos);
            rvListView.setLoadingMoreComplete();
        } else {
            mAdapter.setData(photos);
        }

    }

    private void setToolbarAlpha(int alpha) {
        toolbar.getBackground().setAlpha(alpha);
        ivScan.getDrawable().setAlpha(alpha);
        btnCenter.getBackground().setAlpha(alpha);
        btnCenter.setAlpha(alpha);
        for(Button btn:buttons){
            if(btn!=null){
                btn.getBackground().setAlpha(alpha);
                btn.setAlpha(alpha);
            }
        }

    }

    public void setCurName(String curName) {
        this.curName = curName;
        mHomePresenter.loadPicsForStaggerList(curName);
    }

    @Override
    public void onDestroyView() {
        Log.d("xls","HomeFragment onDestroyView");
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_scan, R.id.fab, R.id.btn_center})
    public void onViewClicked(final View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                intent.setAction(Intents.Scan.ACTION);
                intent.putExtra(Intents.Scan.FORMATS, "QR_CODE");
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.fab:
               /* Snackbar.make(fab, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();*/
                BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {
                    @Override
                    public void onUpdateReturned(int updateStatus, UpdateResponse updateResponse) {
                        LogUtil.d(TAG,"updateStatus = "+updateStatus+", updateResponse="+updateResponse.getException());
                        if (updateStatus == UpdateStatus.Yes) {//版本有更新

                        }else if(updateStatus == UpdateStatus.No){
                            LogUtil.d(TAG,"已是最新版本");
                            Toast.makeText(getContext(), "已是最新版本", Toast.LENGTH_SHORT).show();
                        }else if(updateStatus==UpdateStatus.EmptyField){//此提示只是提醒开发者关注那些必填项，测试成功后，无需对用户提示
                            LogUtil.d(TAG,"请检查你AppVersion表的必填项，1、target_size（文件大小）是否填写；2、path或者android_url两者必填其中一项。");
                        }else if(updateStatus==UpdateStatus.IGNORED){
                            LogUtil.d(TAG,"该版本已被忽略更新");
                            Toast.makeText(getContext(), "该版本已被忽略更新", Toast.LENGTH_SHORT).show();
                        }else if(updateStatus==UpdateStatus.ErrorSizeFormat){
                            LogUtil.d(TAG,"请检查target_size填写的格式，请使用file.length()方法获取apk大小。");
                        }else if(updateStatus==UpdateStatus.TimeOut){
                            LogUtil.d(TAG,"查询出错或查询超时");
                            Toast.makeText(getContext(), "查询出错或查询超时", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                BmobUpdateAgent.forceUpdate(getContext());
                break;
            case R.id.btn_center:
                if(!isCollapsed){
                    return;
                }
                if(buttons.size()==0){
                    initTopButtons();
                }

                String text = btnCenter.getText().toString();
                if(getString(R.string.choose).equals(text)){
                    initTopButtons();
                    doTranslationToLeft(view);
                }else if("?".equals(text)){
                    setCurName(null);
                    doShrinkAnimators();
                }



                break;
        }
    }

    private void doTranslationToLeft(final View view){
        if(view==null){
            return;
        }
        ObjectAnimator animatorTranslation = ObjectAnimator.ofFloat(view, "translationX", 0, -view.getX());
        animatorTranslation.setDuration(200);
        animatorTranslation.setInterpolator(new AccelerateInterpolator());
        animatorTranslation.addListener(new MyAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                LogUtil.d(TAG," onAnimationEnd getX = "+view.getX()+"|getLeft = "+view.getLeft()+"|getTranslationX="+view.getTranslationX());
                for(int i=0;i<buttons.size();i++){
                    buttons.get(i).setVisibility(View.VISIBLE);

                }
                doExpandAnimators();
            }
        });
        animatorTranslation.start();
    }

    private void doTranslationToCenter(View view){
        if(view==null){
            return;
        }
        final ObjectAnimator animatorTranslation = ObjectAnimator.ofFloat(btnCenter,"translationX",btnCenter.getTranslationX(),0);
        animatorTranslation.setDuration(200);
        animatorTranslation.setInterpolator(new DecelerateInterpolator());
        animatorTranslation.start();

    }

    private void doExpandAnimators(){
        if(btnCenter==null){
            return;
        }
        ObjectAnimator animatorRotation = ObjectAnimator.ofFloat(btnCenter, "rotation", 0, 360 * 2);
        animatorRotation.setInterpolator(new DecelerateInterpolator());
        animatorRotation.setDuration(800);
        animatorRotation.addListener(new MyAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                btnCenter.setText("?");
                topState = TopState.EXPAND;
            }
        });
        List<Animator> btnAnimators = new ArrayList<>();
        btnAnimators.add(animatorRotation);
        for(int i=0;i<buttons.size();i++){
            ObjectAnimator animator = ObjectAnimator.ofFloat(buttons.get(i),"translationX",0,detalDistance*(i+1));
            animator.setDuration(600);
            animator.setStartDelay(50);
            animator.setInterpolator(new LinearOutSlowInInterpolator());
            btnAnimators.add(animator);
        }
        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(btnAnimators);
        animatorSet.start();
    }

    private void doShrinkAnimators(){
        if(btnCenter==null){
            return;
        }
        ObjectAnimator animatorRotation = ObjectAnimator.ofFloat(btnCenter, "rotation", 0, -360 * 2);
        animatorRotation.setInterpolator(new DecelerateInterpolator());
        animatorRotation.setDuration(800);
        List<Animator> btnAnimators = new ArrayList<>();
        btnAnimators.add(animatorRotation);
        for(int i=0;i<buttons.size();i++){
            ObjectAnimator animator = ObjectAnimator.ofFloat(buttons.get(i),"translationX",detalDistance*(i+1),0);
            animator.setDuration(600);
            animator.setStartDelay(50);
            animator.setInterpolator(new LinearOutSlowInInterpolator());
            btnAnimators.add(animator);
        }
        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(btnAnimators);
        animatorSet.addListener(new MyAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                doTranslationToCenter(btnCenter);
                btnCenter.setText(R.string.choose);
                topState = TopState.IDLE;
                for(Button button:buttons){
                    if(button.getTag().equals(curName)){
                        button.setVisibility(View.VISIBLE);
                    }else{
                        button.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        animatorSet.start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            // handle scan result
            String content = scanResult.getContents();
            if (TextUtils.isEmpty(content)) {
                return;
            }
            openURL(content);
            Log.d("xls", "onActivityResult ,scanResult  =" + scanResult.toString());
        }
    }

    final void openURL(String url) {
        // Strangely, some Android browsers don't seem to register to handle HTTP:// or HTTPS://.
        // Lower-case these as it should always be OK to lower-case these schemes.
        if (url.startsWith("HTTP://")) {
            url = "http" + url.substring(4);
        } else if (url.startsWith("HTTPS://")) {
            url = "https" + url.substring(5);
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        try {
            launchIntent(intent);
        } catch (ActivityNotFoundException ignored) {
            Log.w(TAG, "Nothing available to handle " + intent);
        }
    }

    final void launchIntent(Intent intent) {
        try {
            rawLaunchIntent(intent);
        } catch (ActivityNotFoundException ignored) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.app_name);
            builder.setMessage(R.string.msg_intent_failed);
            builder.setPositiveButton(R.string.button_ok, null);
            builder.show();
        }
    }

    final void rawLaunchIntent(Intent intent) {
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            Log.d(TAG, "Launching intent: " + intent + " with extras: " + intent.getExtras());
            getActivity().startActivity(intent);
        }
    }


    Class<? extends ViewPager.PageTransformer> getRandomPageTransformer() {
        List<Class<? extends ViewPager.PageTransformer>> transformerList = new ArrayList<>();
        transformerList.add(Transformer.Accordion);
        transformerList.add(Transformer.BackgroundToForeground);
        transformerList.add(Transformer.CubeIn);
        transformerList.add(Transformer.CubeOut);
        transformerList.add(Transformer.Default);
        transformerList.add(Transformer.DepthPage);
        transformerList.add(Transformer.FlipHorizontal);
        transformerList.add(Transformer.RotateDown);
        transformerList.add(Transformer.ScaleInOut);
        transformerList.add(Transformer.RotateUp);
        transformerList.add(Transformer.ForegroundToBackground);
        transformerList.add(Transformer.Stack);
        transformerList.add(Transformer.Tablet);
        transformerList.add(Transformer.ZoomIn);
        transformerList.add(Transformer.ZoomOut);
        transformerList.add(Transformer.ZoomOutSlide);
        int position = new Random().nextInt(16);
        Log.d(TAG, "position = " + position);
        return transformerList.get(position);
    }

    class TopButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Log.d("home","点击 topButton "+v.getTag());
            if(!isCollapsed){
                return;
            }
            if(topState==TopState.EXPAND){
                setCurName((String) v.getTag());
                doShrinkAnimators();
            }

        }
    }


    private Button createTopButton(ViewGroup container,String name){
        Button button = new Button(getContext());
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(72,72);
        layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToBottom =ConstraintLayout.LayoutParams.PARENT_ID;
        button.setText(getKeyName(name));
        button.setTag(name);
        button.setPadding(0,0,0,0);
        button.setGravity(Gravity.CENTER);
        button.setTextColor(getResources().getColor(R.color.white));
        button.setVisibility(View.GONE);
        button.setHeight(ScreenUtil.dip2Px(42,getContext()));
        button.setWidth(ScreenUtil.dip2Px(42,getContext()));
        button.setBackgroundResource(R.drawable.bg_button);
        container.addView(button,layoutParams);
        button.setOnClickListener(topButtonListener);
        return button;
    }

    /**
     * 获取名字的关键字
     * @param name
     * @return
     */
    private String getKeyName(String name){
        if(TextUtils.isEmpty(name)){
            return "?";
        }
        return name.substring(name.length()-1);
    }

}
